package cn.com.dashihui.api.Quartz;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;


import cn.com.dashihui.api.dao.Goods;

public class GiveTask {
	
	 //创建调度器 Scheduler
    protected static StdSchedulerFactory schedulerFactory = new StdSchedulerFactory();
    protected  Scheduler scheduler ;
    
    public GiveTask(){
    	init();
    }
    
    
    public  void init(){
    	try {
			scheduler = schedulerFactory.getScheduler();
			scheduler.start();
		} catch (SchedulerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
   /**
     * 启动调用  TODO
     */
	public  int addTaskList(){
		
		//筛选出来时间比现在晚的
		String sql = "SELECT * FROM t_bus_goods WHERE state=? AND groupbuying=? AND gbmethod=? AND countnum>? AND gbendtime>?";
		List<Goods> goods = Goods.me().find(sql,2,2,2,0,new Date());
		System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+goods.size());
		if ( goods!=null && goods.size()>0){
			goods.stream().forEach(good->{
				addTask(good); 
			});
		}
		return 1;
	}
	/**
	 * 给good加job
	 * @param good
	 */
	public  void addTask(Goods good) {
		try {
			List<Goods> list = new ArrayList<Goods>();
			list.add(good);
			int id = good.getInt("id");
			Date doTime = good.getDate("gbendtime");
			System.out.println("开始时间："+doTime+"id:"+id);
		    //创建JobDetail（任务） 实例
		    JobDetail jobDetail = JobBuilder.
		    		newJob(groupJob.class).
		    		withIdentity("job"+id, "jobGroup"+id).
		    		usingJobData("Goods",id).
		    		build();
		    
		    //创建Trigger（触发器）实例
		    SimpleTrigger trigger = TriggerBuilder.
		    		newTrigger().
		    		withIdentity("trigger"+id, "triggerGroup"+id).
		    		startAt(doTime).
		    		endAt(doTime).
		    		withSchedule(SimpleScheduleBuilder.simpleSchedule().
		    				withIntervalInSeconds(1)).
		    		build();
		    scheduler.scheduleJob(jobDetail,trigger);
		    System.out.println("========= job start ========= ");
		} catch (SchedulerException e) {
			throw new RuntimeException("定时器异常："+e.getMessage()+"     >>>id:"+good.getInt("id"));
		}
	}
	/**
	 * 移除触发器
	 * @param id
	 */
	public  void removeTesk(int id){
		try {
			if(scheduler != null){
				TriggerKey triggerKey = TriggerKey.triggerKey("trigger"+id, "triggerGroup"+id);
	            // 停止触发器
	            scheduler.pauseTrigger(triggerKey);
	            // 移除触发器
	            scheduler.unscheduleJob(triggerKey);
	            // 删除任务
	            scheduler.deleteJob(JobKey.jobKey("job"+id, "jobGroup"+id));
			}
			
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
	}
	
}
